package com.example;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUtil;

public class ExampleMain {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        persistEmployee(emf);
        emf.close();
    }
    private static void persistEmployee(EntityManagerFactory emf){
        Employee employee1 = new Employee("Joe","IT",Phone.cell("111-111-111"),
                Phone.work("222-222-222"));
        printLoadState("New Entity:" ,employee1);
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        em.persist(employee1);
        em.getTransaction().commit();
        em.close();
        printLoadState("Detach entity after EntityManager.close",employee1);

    }
    private static void printLoadState(String msg,Employee employee){
        System.err.println("--- " + msg + " ---");
        PersistenceUtil pu = Persistence.getPersistenceUtil();
        boolean isLoaded = pu.isLoaded(employee);
        System.err.println("employee loaded:" + isLoaded);
        boolean phonesIsLoaded = pu.isLoaded(employee,"phones");
        System.err.println("employee.phones loaded:" + phonesIsLoaded);
    }
}
